package reflect;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * Created by 5406160@qq.com on LiBoWen 李博闻.
 *
 * @ClassName : ConstructorTest
 * @Author : 54061
 * @Date: 2022/2/28 15:12
 */
/*
junit单元测试方法的格式
@Test
public void 方法名(){}
获取Class对象所对应类型中所有公共的构造器
Constructor<?>[] getConstructors();
获取Class对象所对应类型中所有的构造器;
Constructor<?>[] getDeclaredConstructors();
获取Class对象所对应的类型中所有构造器中的某一个,参数为指定构造器中的参数类型的Class
Constructor<T> getDeclaredConstructor(Class<?>...parameterTypes)

 */
public class ConstructorTest {

    @Test
    public void testGetConstructors(){
        //获取Student类型的Class对象
        Class<Student> clazz1 = Student.class;
        Constructor<?>[] constructors = clazz1.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }
        System.out.println("++++++++++++++++++++++++++++++++++++++++++");
        Constructor<?>[] declaredConstructors = clazz1.getDeclaredConstructors();
        for (Constructor<?> declaredConstructor : declaredConstructors) {
            System.out.println(declaredConstructor);
        }
    }

    @Test
    public void testNoArgsConstuctor() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<?> clazz = Class.forName("reflect.Student");
        Constructor<?> constructor = clazz.getConstructor();
        Student student = (Student) constructor.newInstance();
        System.out.println(student);
    }

    @Test
    public void testHasArgsConstructor() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<Student> clazz = Student.class;
        Constructor<Student> constructor = clazz.getDeclaredConstructor(String.class);
        Student student = constructor.newInstance("小明");
        System.out.println(student);
    }

    @Test
    public void testGetPrivateConstructor() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<Student> clazz = Student.class;
        Constructor<Student> constructor = clazz.getDeclaredConstructor(Integer.class, String.class);
        //忽略构造器的访问修饰符
        constructor.setAccessible(true);
        Student student = constructor.newInstance(1001, "小红");
        System.out.println(student);
    }
}